package com.lazy.utils.mail;

import com.lazy.utils.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 发送邮件service
 * @author zk
 * @since  2018-05-22 18:39
 */
@Service
public class MailSentService extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(MailSentService.class);

    @Autowired
    private SimpleMailSender simpleMailSender;


    /**
     * 同步发送邮件
     *
     * @param toAddress
     * @param subject
     * @param content
     */
    public void sendMail(String toAddress, String subject, String content) {
        try {
            this.sendTextMail(toAddress, subject, content);
            logger.debug("toAddress={},subject={},content概要={}", toAddress, subject, StringUtil.limitTo(content, 256));
        } catch (Exception e) {
            logger.error("toAddress={},subject={},content概要={}", toAddress, subject, StringUtil.limitTo(content, 256));
        }
    }

    /**
     * 发送邮件(支持Text格式)
     *
     * @param toAddress(aa@letv.com,bb@letv.com)
     * @param subject                            主题
     * @param content                            正文
     */
    public void sendTextMail(String toAddress, String subject, String content) throws Exception {
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.exmail.qq.com");
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("xx@qq.com");
        mailInfo.setPassword("123456");// 您的邮箱密码
        mailInfo.setFromAddress("xx@qq.com");
        mailInfo.setToAddress(toAddress);
        mailInfo.setSubject(subject);
        mailInfo.setContent(content);
        simpleMailSender.sendTextMail(mailInfo);
    }

    public static void main(String[] args) {
        SimpleMailSender simpleMailSender = new SimpleMailSender();
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.exmail.qq.com");
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("xx@qq.com");
        // 您的邮箱密码
        mailInfo.setPassword("xOV7dhul");
        mailInfo.setFromAddress("xx@qq.com");
        mailInfo.setToAddress("abc@qq.com");
        mailInfo.setSubject("zk123456");
        mailInfo.setContent("test");
        simpleMailSender.sendTextMail(mailInfo);
    }
}
